package com.dhl.fin.api.service;

import com.dhl.fin.api.common.service.CommonService;
import com.dhl.fin.api.common.util.ArrayUtil;
import com.dhl.fin.api.common.util.ObjectUtil;
import com.dhl.fin.api.common.util.WebUtil;
import com.dhl.fin.api.domain.Project;
import com.dhl.fin.api.domain.Role;
import com.dhl.fin.api.domain.Tree;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by CuiJianbo on 2020.02.23.
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class RoleServiceImpl extends CommonService<Role> {

    @Autowired
    TreeServiceImpl treeService;


    @Autowired
    ActionServiceImpl actionService;


    /**
     * 在保存前
     *
     * @param domain
     */
    @Override
    public void beforeSave(Role domain) throws Exception {
        Long projectId = WebUtil.getLongParam("projectId");
        domain.setProject(new Project(projectId));
    }

    /**
     * 保存后
     *
     * @param domain
     */
    @Override
    public void afterSave(Role domain) throws Exception {
        Long[] treeIds = WebUtil.getLongArrayParam("roleTreeIds");
        if (ArrayUtil.isNotEmpty(treeIds)) {
            List<Tree> trees = findDomainListByIds(Arrays.asList(treeIds), Tree.class);
            if (ObjectUtil.notNull(trees)) {
                domain.setTrees(trees);
            }
        }

        Long[] dataTreeIds = WebUtil.getLongArrayParam("dataTreeIds");
        if (ArrayUtil.isNotEmpty(dataTreeIds)) {
            List<Tree> trees = findDomainListByIds(ArrayUtil.arrayToList(dataTreeIds), Tree.class);
            if (ObjectUtil.notNull(trees)) {
                domain.setDataPerTrees(trees);
            }
        }

        saveOrUpdate(domain);
    }


    @Override
    public void afterGet(Role domain) throws Exception {
        if (ObjectUtil.notNull(domain.getTrees())) {
            List<Long> treeIds = domain.getTrees().stream().map(Tree::getId).collect(Collectors.toList());
            domain.setActionTreeIds(treeIds);
        }
        if (ObjectUtil.notNull(domain.getDataPerTrees())) {
            List<Long> treeIds = domain.getDataPerTrees().stream().map(Tree::getId).collect(Collectors.toList());
            domain.setDataPerTreeIds(treeIds);
        }
    }


}




